import sys
import pygame

from settings import Settings
from ultraman import Ultraman

class UltramanVsMonster:
    """管理游戏资源和⾏为的类"""

    def __init__(self):
        """初始化游戏并创建游戏资源"""
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))

        pygame.display.set_caption("ultraman_vs_monster")
        self.clock = pygame.time.Clock()
        self.ultraman = Ultraman(self)

    def run_game(self):
        """开始游戏的主循环"""
        while True:
            # 侦听键盘和⿏标事件
            self._check_events()

            self.ultraman.update()

            self._update_screen()

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
              
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
                

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            # 向右移动
            self.ultraman.moving_right = True
        elif event.key == pygame.K_LEFT:
            # 向左移动
            self.ultraman.moving_left = True
        elif event.key == pygame.K_UP:
            self.ultraman.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.ultraman.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            # 停止向右移动
            self.ultraman.moving_right = False
        elif event.key == pygame.K_LEFT:
            # 停止向左移动
            self.ultraman.moving_left = False
        elif event.key == pygame.K_UP:
            self.ultraman.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.ultraman.moving_down = False

    def _update_screen(self):
        # 让最近绘制的屏幕可⻅
        self.screen.fill(self.settings.bg_color)
        self.ultraman.blitme()

        pygame.display.flip()
        self.clock.tick(60)


if __name__ == "__main__":
    # 创建游戏实例并运⾏游戏
    ai = UltramanVsMonster()
    ai.run_game()
